var ge;
google.load("earth", "1");

function init() {
    google.earth.createInstance('map3d', initCB, failureCB);
}

function initCB(instance) {
    ge = instance;
    /* Start the COP loading */
    fetchKML(ge);
    /* Set options */
    ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
    ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
    opts = ge.getOptions()
    opts.setScaleLegendVisibility(true);
    opts.setStatusBarVisibility(true);
    opts.setOverviewMapVisibility(true);
    google.earth.addEventListener(ge.getWindow(), 'mousedown', mouseDownListener);
    google.earth.addEventListener(ge.getGlobe(), 'mousemove', mouseMoveListener);
    google.earth.addEventListener(ge.getWindow(), 'mouseup', mouseUpListener);
    ge.getWindow().setVisibility(true);
    /*DEBUG*/
    // Get the current view
    var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_ABSOLUTE);

    // Set new latitude and longitude values
    lookAt.setLatitude(2);
    lookAt.setLongitude(2);
    lookAt.setAltitude(2100000);
    lookAt.setRange(0);

    // Update the view in Google Earth
    ge.getView().setAbstractView(lookAt);
}

function failureCB(errorCode) {
}

function fetchKML(ge) {
    var href = "http://localhost:8080/cop.kml";
    google.earth.fetchKml(ge, href, function(kmlobject) {
        if (kmlobject) {
            ge.getFeatures().appendChild(kmlobject);
        } else {
            alert("Err 001: Failed to load KML");
        }
    });
}


/* Gratuitously stolen from the documentation */
function mouseDownListener(event) {
    if (event.getTarget().getType() == 'KmlPlacemark' &&
    event.getTarget().getGeometry().getType() == 'KmlPoint') {
        var placemark = event.getTarget();
        dragInfo = {
            placemark: event.getTarget(),
            dragged: false
        };
    }
}

// Listen for mousemove on the globe.
function mouseMoveListener(event) {
    if (dragInfo) {
        event.preventDefault();
        var point = dragInfo.placemark.getGeometry();
        point.setLatitude(event.getLatitude());
        point.setLongitude(event.getLongitude());
        dragInfo.dragged = true;
    }
}

// Listen for mouseup on the window.
function mouseUpListener(event) {
    if (dragInfo) {
        if (dragInfo.dragged) {
            // If the placemark was dragged, prevent balloons from popping up.
            event.preventDefault();
            /* Tell the server */
            ObjectPlaced(event.getTarget());
        }
        dragInfo = null;
    }
}

/* Function to pass an object's location to the server */
function ObjectPlaced(obj) {
    var req = new Request({
        url:    "http://localhost:8080/movement",
        data:   {"id":  obj.getId(),
                 "lat": obj.getGeometry().getLatitude(),
                 "lon": obj.getGeometry().getLongitude()
        },
    });
    req.send();
}
google.setOnLoadCallback(init);